package listener.physical;

import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;

import model.Particle;

public class BallCollision implements Observer{
	private static BallCollision collision;
	private static LinkedList<Particle> particleList = new LinkedList<Particle>();

	public static BallCollision getInstance(){
		if(collision==null){
			collision = new BallCollision();
		}
		return collision;
	}
	
	public static void addParticle(Particle p){
		if(!particleList.contains(p)){
			particleList.add(p);
		}
	}
	
	public static void removeParticle(Particle p){
		if(particleList.contains(p)){
			particleList.remove(p);
		}
	}
	
	public void collision(Particle p1,Particle p2){
		//互相碰撞
		double distance = p1.distance(p2);
		if(distance <= (p1.getRadius()+p2.getRadius())){
			double v1x = p1.getVelocity().getX();
			double v1y = p1.getVelocity().getY();
			double v2x = p2.getVelocity().getX();
			double v2y = p2.getVelocity().getY();
			p1.getVelocity().setX(v2x);
			p1.getVelocity().setY(v2y);
			p2.getVelocity().setX(v1x);
			p2.getVelocity().setY(v1y);
		}
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		Particle p = (Particle)arg0;
		String order = (String) arg1;

		if(!p.isDead()){
			addParticle(p);
		}else{
			removeParticle(p);
		}
		if(order.equals("move")){
			if(p.getCollisionCooldown()==0){
				for(Particle p2:particleList){
					if(p2.getCollisionCooldown()==0){
						collision(p,p2);
					}
				}
			}
		}else if(order.equals("")){
			
		}
	}

}
